const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const path = require('path');
const { bailianRouter } = require('./routes/bailian');
const { configRouter } = require('./routes/config');
const { openaiRouter } = require('./routes/openai');

// 加载配置管理器
require('./utils/config-manager');

// Load environment variables
dotenv.config();

// Initialize Express app
const app = express();
const PORT = process.env.PORT || 3001; // 使用 3001 端口避免冲突

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Serve static files
app.use(express.static(path.join(__dirname, 'public')));

// Routes
app.use('/api/bailian', bailianRouter);
app.use('/api/config', configRouter);
app.use('/api/openai', openaiRouter);

// Root route
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Config page route
app.get('/config', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'config.html'));
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error('Error:', err.message);
  res.status(err.status || 500).json({
    error: {
      message: err.message || 'Internal Server Error',
      status: err.status || 500
    }
  });
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`http://localhost:${PORT}`);
});
